﻿from flask import Flask, render_template, jsonify, request, g 
import random
import json

app = Flask(__name__)
DEBUG = True
SECRET_KEY = 'sfsefslejfl'
DATEBASE = 'db.json'
app.config.from_object(__name__)


@app.before_request
def before_request():
	try:
		muser = open(DATEBASE).read()
	except IOError:
		muser = '{"links":[]}'
	g.muser = json.loads(muser)

@app.teardown_request
def teardown_requset(exception):
	if hasattr(g, 'muser'):
		open(DATEBASE, 'w').write(json.dumps(g.muser, indent = 4))

colors = ['#5FD9CD','#EAF786', '#FFB5A1', 
		  '#B8FFB8', '#B8F4FF']

@app.route('/links/<string:item>')
def links_items(item):
	if item == 'index':
		L = g.muser['links']
		def fn(x,y):
			x['hexid'] = y
			x['color'] = random.choice(colors)
			x['hyperlink'] = request.url.replace(
					         'index', x['item'])
			return x
		L = map(fn, L, range(1, len(L)+1))
		other = {'title': u"主页"}
		return render_template('links.html',
								links = L,
								other = other)
	else:
		L = [i['subitem'] for i in g.muser['links'] if i['item'] == item][0]
		def fn(x,y):
			x['hexid'] = y
			x['color'] = random.choice(colors)
			return x
		L = map(fn, L, range(1, len(L)+1))
		other = {'title': item}
		return render_template('links.html',
								links = L,
								other = other)
@app.route('/link/addtype')
def links_addtype():
	a = request.args.get('a', 0)
	g.muser['links'].append({'item':a, 'subitem':[]})
	return jsonify()

@app.route('/link/addlink')
def links_addlink():
	a = request.args.get('a', 0)
	b = request.args.get('b', 0)
	c = request.args.get('c', 0)
	L = [i['subitem'] for i in g.muser['links'] if i['item'] == a][0]
	L.append({"hyperlink":b,"item":c})
	return jsonify()

@app.route('/link/deleteitem')
def links_deleteitem():
	a = request.args.get('a', 0)
	b = request.args.get('b', 0)	
	if b == u"主页":
		L = [i for i in g.muser['links'] if i['item'] == a][0]
		g.muser['links'].remove(L)
	else:
		for i in g.muser['links']:
			for j in i['subitem']:
				if j['item'] == a:
					i['subitem'].remove(j)
	return jsonify()


if __name__ == '__main__':
    app.run(debug=True)

